<template>
  <div
    ref="editor"
    class="editor"
    contenteditable="true"
    v-html="editorText"
    @input="handleInput"
    @focus="handleFocus"
    @blur="handleBlur"
    @keyup.enter="handSubmit"
  ></div>
</template>
 
<script>
export default {
  props: {
    value: { type: String, default: "" }
  },
  data() {
    return {
      editorText: this.value,
      isChange: true,
      range:null
    };
  },
  watch: {
    value() {
      if (this.isChange) {
        this.editorText = this.value;
      }
    }
  },
  methods: {
    handleInput() {
      this.$emit("input", this.$el.innerHTML);
      var sel = window.getSelection();
      this.range = sel.getRangeAt(0);
    },
    handSubmit(){
      this.$emit('submit');
      this.handleClear();
    },
    // 清空编辑器
    handleClear() {
      this.$refs.editor.innerHTML = "";
      this.$refs.editor.focus();
    },

    // 获取焦点
    handleFocus() {
      this.isChange = false;
      this.$emit("focusFn");
    },
    // 失去焦点
    handleBlur() {
      this.isChange = true;
      this.$emit("blurFn");
      // debugger;
      var sel = window.getSelection();
      this.range = sel.getRangeAt(0);
    },

    /**
     * 光标处插入内容
     * @param html 需要插入的内容
     */
    insertHtmlAtCaret(html) {
      // debugger;
      let sel; 
      // range;
      // this.$refs.editor.focus()
      if (!this.$refs.editor.childNodes.length) {

        this.$refs.editor.focus();
      }
      if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();

        if (sel.getRangeAt && sel.rangeCount) {
          if(!this.range){
            this.range = sel.getRangeAt(0);
          }
          // range.deleteContents();
          let el = document.createElement("div");
        
          el.appendChild(html[0]);
          var frag = document.createDocumentFragment(),
            node,
            lastNode;
          while ((node = el.firstChild)) {
            lastNode = frag.appendChild(node);
          }
          this.range.insertNode(frag);
          if (lastNode) {
            this.range =this.range.cloneRange();
            this.range.setStartAfter(lastNode);
            this.range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(this.range);
          }
          this.range = sel.getRangeAt(0);
        }
      } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
      }

      this.handleInput();
    }
  }
};
</script>
 
<style>
.editor {
    width: 100%;
    /* height: 80px; */
    border-top:1px solid #999;
    padding: 30px 10px 0px 10px;
    padding-top: 40px;
    
}
.editor:focus{
  outline: none ;
}
</style>